Learn how to install Phoenix LiveView in new and existing Phoenix applications.
Phoenix LiveView is included by default in Phoenix 1.6+ applications. If you’re creating a new app, you’re all set! For existing applications, this guide will walk you through adding LiveView.
Update your assets/js/app.js to connect to the LiveView socket:
// Import Phoenix and LiveViewimport {Socket} from "phoenix"import {LiveSocket} from "phoenix_live_view"// Get the CSRF token from the page meta taglet csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")// Create and connect the LiveSocketlet liveSocket = new LiveSocket("/live", Socket, { params: {_csrf_token: csrfToken}})// Connect if there are any LiveViews on the pageliveSocket.connect()// Expose liveSocket for web console debuggingwindow.liveSocket = liveSocket
7
Add CSRF meta tag
Ensure your root layout (lib/my_app_web/templates/layout/root.html.heex or similar) includes the CSRF meta tag in the <head>:
This is required for LiveView to authenticate connections.
8
Enable LiveView Flash
Update your app layout to support LiveView flash messages. In your main layout template, add:
<.flash_group flash={@flash} />
Or if using a simpler setup:
<%= if live_flash(@flash, :info) do %> <p class="alert alert-info" role="alert"><%= live_flash(@flash, :info) %></p><% end %><%= if live_flash(@flash, :error) do %> <p class="alert alert-danger" role="alert"><%= live_flash(@flash, :error) %></p><% end %>
For a better development experience, add these helpers to your lib/my_app_web.ex file:
def live_view do quote do use Phoenix.LiveView, layout: {MyAppWeb.Layouts, :app} unquote(html_helpers()) endenddef live_component do quote do use Phoenix.LiveComponent unquote(html_helpers()) endend
Then in your LiveViews, you can use:
defmodule MyAppWeb.SomeLive do use MyAppWeb, :live_view # ...end
WebSocket connection fails: Ensure your endpoint is configured to handle WebSocket upgrades. Check your web server configuration if using a reverse proxy.“Unauthorized” errors: Verify the CSRF token is correctly passed from the meta tag to the LiveSocket configuration.LiveView not updating: Make sure you’re returning the updated socket from your event handlers with {:noreply, socket}.